/*
 * Copyright 2009 Google Inc.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.appengine.demos.oauth;

import com.google.appengine.api.oauth.InvalidOAuthParametersException;
import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.appengine.api.oauth.OAuthServiceFailureException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Simple servlet to demonstrate the OAuth signature checking API.
 * 
 * See http://code.google.com/intl/en/appengine/docs/java/oauth/.
 */
public class VerifyServlet extends HttpServlet {

  private static final Logger logger = Logger.getLogger(VerifyServlet.class.getName());

  @Override
  public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
    JsonObject output = new JsonObject();
    try {
      OAuthService oauthService = OAuthServiceFactory.getOAuthService();
      String consumerId = oauthService.getOAuthConsumerKey();
      output.addProperty("status", "ok");
      output.addProperty("consumer_key", consumerId);
      JsonObject arguments = new JsonObject();
      for (Entry<String, String[]> arg : getParameterMap(req).entrySet()) {
        JsonArray array = new JsonArray();
        arguments.add(arg.getKey(), array);
        for (String value : arg.getValue()) {
          array.add(new JsonPrimitive(value));
        }
      }
      output.add("arguments", arguments);
      res.setStatus(HttpServletResponse.SC_OK);
      logger.log(Level.INFO, "request was signed by " + consumerId);
    } catch (InvalidOAuthParametersException e) {
      res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      output.addProperty("status", "invalid parameters");
      logger.log(Level.INFO, "request validation failure", e);
    } catch (OAuthRequestException e) {
      res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      output.addProperty("status", "invalid request");
      logger.log(Level.INFO, "request validation failure", e);
    } catch (OAuthServiceFailureException e) {
      res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      output.addProperty("status", "unexpected error");
      logger.log(Level.INFO, "request validation failure", e);
    }
    res.setHeader("Content-Type", "application/json");
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    res.getWriter().write(gson.toJson(output));
  }
    
  @SuppressWarnings("unchecked")
  Map<String, String[]> getParameterMap(HttpServletRequest req) {
    return req.getParameterMap();
  }
}
